package com.iptv.grape.ui.frgmt;

import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.iptv.grape.BaseActivity;
import com.iptv.grape.R;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.bu.imp.QuitBackMode;
import com.iptv.grape.domain.Channel;
import com.iptv.grape.domain.ChannelBill;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.event.data.BackLiveData;
import com.iptv.grape.event.data.VodData;
import com.iptv.grape.ui.BaseFrgmt;
import com.iptv.grape.util.AppConstant;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.view.CenterLayoutManager;
import com.iptv.grape.ui.control.INextFocus;
import com.iptv.grape.view.LongEnterRecycleView;
import com.iptv.grape.view.XSeekBar;
import com.iptv.grape.ui.control.ad.LabelAdapter;
import com.iptv.grape.util.CommUtil;
import com.iptv.grape.video.IPlayerListener;
import com.iptv.grape.video.XMediaPlayer;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.List;

// 回看底部Fragment
public class ChannelBillFragment extends BaseFrgmt implements SeekBar.OnSeekBarChangeListener,
        IPlayerListener, INextFocus,
        View.OnFocusChangeListener{
    // 回看的频道
    private Channel channel;
    // 回看的时间天数字符串
    private String dateTimeString;
    // 频道所属的当天的节目单
    private List<ChannelBill> channelBills;
    // 当前被选择的节目单
    private ChannelBill selectBill;

    // 显示的TextView title
    private TextView titleTextView;
    //
    private TextView date_top;

    private TextView time_left;
    private TextView time_right;
    private TextView timing;
    //private HorizontalListView rel_horitation;
    //private HorizontalListViewAdapter adapter;

    private LongEnterRecycleView rel_horitation;
    private LabelAdapter adapter;

    private XSeekBar seekbar;


    // 当前正在播放的ID
    private int selectIndex = 0;

    public ChannelBill getSelectBill() {
        return selectBill;
    }

    public void setSelectBill(ChannelBill selectBill) {
        this.selectBill = selectBill;
    }

    public void setSelectIndex(int pos){
        this.selectIndex = pos;
    }

    public void setChannelBills(List<ChannelBill> channelBills){
        this.channelBills = channelBills;
    }

    // 构造函数
    public ChannelBillFragment(){

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.dateTimeString = getArguments().getString("dateTimeString");  //获取参数
        this.channel = GrapeContext.curGrapeContext().getChannelDLinkList().getCurChannel();
    }


    @Override
    protected int layoutId() {
        return R.layout.bill_list_fragment;
    }

    @Override
    protected void initView(@NonNull View root, @Nullable Bundle savedInstanceState) {
        titleTextView = root.findViewById(R.id.titleTextView);
        date_top = root.findViewById(R.id.date_top);
        time_left = root.findViewById(R.id.time_left);
        time_right = root.findViewById(R.id.time_right);
        timing = root.findViewById(R.id.timing);
        seekbar = root.findViewById(R.id.seekbar);
        seekbar.setTag("seekbar");

        seekbar.setOnSeekBarChangeListener(this);
        seekbar.setOnFocusChangeListener(this);

        rel_horitation = root.findViewById(R.id.rel_horitation);
        rel_horitation.setTag("list");
        rel_horitation.setOnFocusChangeListener(this);
        //seekbar.setNextCon(rel_horitation);
        seekbar.setOnNextFocusListener(this);
        GrapeContext.curGrapeContext().getCurMediaPlayer().setSeekbar(seekbar);
        GrapeContext.curGrapeContext().getCurMediaPlayer().setOnPlayerListener(this);
        //seekbar.setKeyProgressIncrement(5000);
        // 设置界面上的文本
        setUIAttr();
        // 设置节目单列表为横向
        LinearLayoutManager centerLayoutManager = new CenterLayoutManager(this.mActivity, LinearLayoutManager.HORIZONTAL, false);
        rel_horitation.setLayoutManager(centerLayoutManager);
        // 构造适配器
        adapter = new LabelAdapter(inflater,mActivity,this.channelBills,this.selectBill);
        //AppLog.getCurLog().out("共" + this.channelBills.size() + "个节目单");
        rel_horitation.setAdapter(adapter);
        // 设置节目单列表控件属性
        rel_horitation.setItemCount(this.channelBills.size());
        rel_horitation.setCurIndex(selectIndex);
        this.rel_horitation.setCurPlayIndex(selectIndex);
        // 设置事件监听 界面单单击事件
        adapter.setOnLabelClickListener(new LabelAdapter.OnLabelClickListener() {
            @Override
            public void onClick(ChannelBill channelBill, int position) {
                ChannelBillFragment.this.playChannelBill(channelBill,position);
            }
        });
        rel_horitation.initScrollToPosition();

        // 延时让进度条获得焦点
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                seekbar.requestFocus();

            }
        }, 100);
        //seekbar.requestFocus();

        BackLiveData.createBackLiveData(this.channel,this.selectBill);

    }


    // 进度条上按下方向键 下键时给列表控件最后一次获得焦点的元素 落焦
    @Override
    public void toNextFocus() {
        rel_horitation.getCurLabelHolderRequestFocus();
    }

    // 销毁
    public void onDestroy() {
        super.onDestroy();
        GrapeContext.curGrapeContext().getCurMediaPlayer().cleanSeekbar();
        GrapeContext.curGrapeContext().getCurMediaPlayer().removeListener(this);
    }


    public void setUIAttr(){
        // 节目单的标题
        titleTextView.setText(this.selectBill.getName());
        // 节目单时间段日期(yyyy-mm-dd)
        date_top.setText(this.dateTimeString);
        // 开始时间（HH:mm）
        time_left.setText(CommUtil.formatDate(this.selectBill.getBillStartDate(),"HH:mm"));
        // 结束时间（HH:mm)
        time_right.setText(CommUtil.formatDate(this.selectBill.getBillEndDate(),"HH:mm"));
        // 进度条游标(HH:MM:SS)
        timing.setText(CommUtil.formatDate(this.selectBill.getBillStartDate(),"HH:mm:ss"));
    }

    public void playChannelBill(ChannelBill channelBill, int position){
        String billType = channelBill.getBillType();
        if(billType.equals("before")) {
            XMediaPlayer mediaPlayer = GrapeContext.curGrapeContext().getCurMediaPlayer();
            if (mediaPlayer != null) {
                ChannelBillFragment.this.selectBill = channelBill;
                BackLiveData.createBackLiveData(this.channel,this.selectBill);
                this.selectIndex = position;
                ChannelBillFragment.this.adapter.setSelectChannelBill(channelBill);
                this.rel_horitation.setViewHolderBackground(billType);
                this.rel_horitation.setCurPlayIndex(position);
                this.rel_horitation.setViewHolderBackgroundByPlay();
                String playUrl = ChannelBillFragment.this.channel.getRuAddress() + channelBill.getArgs();
                mediaPlayer.stop();
                mediaPlayer.play(GrapeContext.curGrapeContext().getCurActivity(), playUrl);
                setUIAttr();
            }
        }else if(billType.equals("now")){
            //GrapeContext.curGrapeContext().hiddLiveMenu((BaseActivity) this.mActivity);
            QuitBackMode.execQuitBackMode((BaseActivity) this.mActivity);
        }
        else {
            // 预约

        }
    }


    public static ChannelBillFragment newInstance(String dateTimeString) {
        ChannelBillFragment frag = new ChannelBillFragment();
        Bundle bundle = new Bundle();
        bundle.putString("dateTimeString", dateTimeString);
        frag.setArguments(bundle);   //设置参数
        return frag;
    }

    // 界面隐藏显示回调函数
    @Override
    public void onHiddenChanged(boolean hidden){
        super.onHiddenChanged(hidden);
        // 不在最前端界面显示
        if (hidden) {
            // 隐藏
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //rel_horitation.reSetFocus();
                    seekbar.requestFocus();

                }
            }, 100);
        }
    }

    // 数据上报 Handler
    private Handler datalHandler = new Handler();

    // 数据上报 Runnable
    private Runnable backDataHandlerRunnable = new Runnable() {

        @Override
        public void run() {
            if(BackLiveData.getCurBackLiveData() != null){
                BackLiveData backLiveData = BackLiveData.getCurBackLiveData();
                backLiveData.setProgramOperateType(lastVal);
                EventBus.getDefault().post(new EventArgs(AppConstant.Back,
                        AppConstant.DataAcquisition, backLiveData));
            }
        }
    };
    int lastVal;

    // 进度条事件监听实现 start
    // 进度改变
    @Override
    public synchronized void onProgressChanged(SeekBar seekBar, int progressVal, boolean isUserSet) {

        if(isUserSet) {
            XMediaPlayer mediaPlayer = GrapeContext.curGrapeContext().getCurMediaPlayer();
            if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
            }
            lastVal = progressVal - mediaPlayer.getCurrentPosition() > 0 ? 1:2;
            mediaPlayer.seekTo(progressVal);
            datalHandler.removeCallbacks(backDataHandlerRunnable);
            //curChannel.playTimeMove(curTimeArga);
            datalHandler.postDelayed(backDataHandlerRunnable,200);
        }
        // 进度条游标(HH:MM:SS)
        //timing.setText(CommUtil.formatDate(selectBill.getBillStartDate(),"HH:mm:ss"));
        int quotaWidth = timing.getWidth();
        final Drawable thumb = seekBar.getThumb();
        //获取thumb的位置
        final Rect bounds = thumb.getBounds();

        Date tmpCurStartDate =  this.selectBill.getNewBillStartDate();
        tmpCurStartDate.setTime(tmpCurStartDate.getTime() + progressVal);
        //curStartDate.setTime(curStartDate.getTime() + i);
        timing.setText(CommUtil.formatDate(tmpCurStartDate,"HH:mm:ss"));
        timing.setX((thumb.getIntrinsicWidth() - quotaWidth) / 2
                + bounds.left + seekBar.getX());
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    // 进度条事件监听实现 end

    // 进度条事件焦点事件监听实现 start
    // 进度条获得焦点事件
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
//        if(view.getTag() !=null){
//            AppLog.getCurLog().out(view.getTag().toString());
//        }
        if(hasFocus){
            this.rel_horitation.setHasFocus(false);
            timing.setBackgroundResource(R.drawable.timing_fucs);
            timing.setTextColor(this.mActivity.getResources().getColor(R.color.white));
        }else {
            this.rel_horitation.setHasFocus(true);
            timing.setBackgroundResource(R.drawable.timing_blus);
            timing.setTextColor(this.mActivity.getResources().getColor(R.color.item_bill4));
        }
    }

    // 进度条事件焦点事件监听实现 end

    // 播放器相关事件接口实现 start

    // 播放完成
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 90:
                    if(selectIndex + 1 >= channelBills.size()){
                        // 没有下一个节目单
                        // 返回直播
                        // 执行返回直播命令
                        QuitBackMode.execQuitBackMode((BaseActivity) mActivity);
                    }else {
                        selectIndex++;
                        selectBill = channelBills.get(selectIndex);
                        rel_horitation.scrollToNext(selectIndex);
                        playChannelBill(selectBill,selectIndex);

                    }
                    break;
            }
        }
    };

    @Override
    public void playCompletion(){
        // 回看节目单播放完成
        // 播放下一个
        Message message = mHandler.obtainMessage(90);
        mHandler.sendMessage(message);

    }
    @Override
    public void onStop(int speed) {
        AppLog.getCurLog().out("回看停止");
        if(BackLiveData.getCurBackLiveData() != null){
            BackLiveData backLiveData = BackLiveData.getCurBackLiveData();
            backLiveData.setState("1");
            EventBus.getDefault().post(new EventArgs(AppConstant.Back,
                    AppConstant.DataAcquisition, backLiveData));
        }
    }

    @Override
    public void onStart(){
        super.onStart();
    }

    @Override
    public  void  onResume(){
        super.onResume();
    }

    @Override
    public void onPlaying() {
        AppLog.getCurLog().out("回看开始播放");
        if(BackLiveData.getCurBackLiveData() != null){
            BackLiveData backLiveData = BackLiveData.getCurBackLiveData();
            backLiveData.setState("0");
            backLiveData.setProgramOperateType(0);
            EventBus.getDefault().post(new EventArgs(AppConstant.Back,
                    AppConstant.DataAcquisition, backLiveData));
        }
    }

    @Override
    public void onPlayPause() {
        AppLog.getCurLog().out("回看暂停");
        if(BackLiveData.getCurBackLiveData() != null){
            BackLiveData backLiveData = BackLiveData.getCurBackLiveData();
            backLiveData.setProgramOperateType(3);
            EventBus.getDefault().post(new EventArgs(AppConstant.Back,
                    AppConstant.DataAcquisition, backLiveData));
        }
    }



    @Override
    public void onError() {

    }

    @Override
    public void onProgress(int speed) {
        //seekbar.setProgress(speed);
    }

    @Override
    public void onIntoFullScreen() {

    }

    @Override
    public void onQuitFullScreen() {

    }



    // 播放器相关事件接口实现 end
}
